package com.xnck.demo.exportword.impl;


import com.xnck.demo.ConfigConst;
import com.xnck.demo.exportword.IExportWord;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.Map;

public class FTLExportWord implements IExportWord{

    private static Template t;

    private Configuration createConfig() throws IOException {
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
        configuration.setDefaultEncoding("UTF-8");
        configuration.setClassForTemplateLoading(FTLExportWord.class, ConfigConst.TEMPLATE_PACK);
        configuration.setClassicCompatible(true);
        return configuration;
    }

    private Template createTemplate() throws IOException {
        Configuration configuration = createConfig();
        Template template = configuration.getTemplate(ConfigConst.FTL_TEMPLATE_TEST);
        t = template;
        return t;
    }

    public void exportWord(String outPath, Map<String, Object> dataMap) throws Exception {
        if (null == t){
            createTemplate();
        }
        File outFile = new File(outPath);
        if (!outFile.getParentFile().exists()){
            outFile.getParentFile().mkdirs();
        }
        FileOutputStream fos = new FileOutputStream(outFile);
        OutputStreamWriter oWriter = new OutputStreamWriter(fos,"utf-8");
        Writer out = new BufferedWriter(oWriter);
        t.process(dataMap, out);
    }
}
